package com.bscc.admin.industry;

import com.bscc.common.model.Industry;
import com.jfinal.plugin.activerecord.Db;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class IndustryService
{
    private static final Industry dao = new Industry().dao();

    public List<Industry> findList()
    {
        List<Industry> industryList = dao.find("SELECT * FROM bw_industry ORDER BY id");
        countChild(industryList);
        List<Industry> sortedList = new ArrayList<Industry>();
        sortForTree(sortedList, industryList, 0);
        return sortedList;
    }

    public Industry findById(int id)
    {
        Industry industry= dao.findById(id);
        if(null != industry && null != industry.getPid() && 0 != industry.getPid())
        {
            Industry pIndustry = dao.findById(industry.getPid());
            if(null != pIndustry)
            {
                industry.setPname(pIndustry.getName());
            }
        }
        return industry;
    }

    public void save(Industry industry)
    {
        industry.save();
        if(null == industry.getPid() || 0 == industry.getPid())
        {
            industry.setPid(0);
            industry.setPids("0,"+industry.getId());
        }
        else
        {
            Industry parent = findById(industry.getPid());
            if(null != parent && StringUtils.isNotBlank(parent.getPids()))
                industry.setPids(parent.getPids()+","+industry.getId());
        }
        industry.update();
    }

    public void update(Industry industry)
    {
        industry.update();
    }

    public void deleteById(int id)
    {
        String pids = findById(id).getPids();
        Db.update("DELETE FROM bw_industry WHERE pids LIKE ?", pids+"%");
    }

    private void countChild(List<Industry> industryList)
    {
        if(null != industryList && industryList.size() > 0)
        {
            for(int i=0; i < industryList.size(); ++i)
            {
                int count = 0;
                for(Industry idu:industryList)
                {
                    if(idu.getPid().equals(industryList.get(i).getId()))
                        ++count;
                }
                industryList.get(i).setChildCount(count);
            }
        }
    }

    private void sortForTree(List<Industry> res, List<Industry> src, int pid)
    {
        if(null != src && src.size() > 0)
        {
            for(Industry m: src)
            {
                if(pid == m.getPid())
                {
                    res.add(m);
                    sortForTree(res, src, m.getId());
                }
            }
        }
    }
}
